package com.example.exam.servlet;

import com.example.exam.dao.ExamDAO;
import com.example.exam.dao.ScoreDAO;
import com.example.exam.entity.Exam;
import com.example.exam.entity.Question;
import com.example.exam.entity.Score;
import com.example.exam.entity.Student;
import com.example.exam.dao.QuestionDAO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 考试Servlet
 */
@WebServlet("/exams/*")
public class ExamServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private ExamDAO examDAO = new ExamDAO();
    private ScoreDAO scoreDAO = new ScoreDAO();
    private QuestionDAO questionDAO = new QuestionDAO();
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 获取请求路径
        String pathInfo = request.getPathInfo();
        HttpSession session = request.getSession(false);

        if (session == null || session.getAttribute("student") == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }
        Student student = (Student) session.getAttribute("student");

        if (pathInfo == null || pathInfo.equals("/")) {
            // 获取所有可用考试
            List<Exam> exams = examDAO.getAvailableExams(student.getStudentId());
            request.setAttribute("exams", exams);
            
            // 转发到考试列表页面
            request.getRequestDispatcher("/WEB-INF/views/exams.jsp").forward(request, response);
        } else if (pathInfo.startsWith("/take/")) {
            // 获取考试ID
            String examIdStr = pathInfo.substring(pathInfo.lastIndexOf('/') + 1);
            try {
                int examId = Integer.parseInt(examIdStr);
                
                // 获取考试信息
                Exam exam = examDAO.getExamById(examId);
                if (exam == null) {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, "找不到该考试");
                    return;
                }
                
                // 获取当前时间
                LocalDateTime now = LocalDateTime.now();
                
                // 检查考试状态和时间窗口
                if (!"active".equals(exam.getStatus())) {
                    request.setAttribute("error", "该考试当前未激活，请联系管理员。");
                    forwardToExamsPage(request, response, student.getStudentId());
                    return;
                }
                
                if (now.isBefore(exam.getStartTime())) {
                    request.setAttribute("error", "考试尚未开始，请于 " + exam.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")) + " 后再试。");
                    forwardToExamsPage(request, response, student.getStudentId());
                    return;
                }

                if (now.isAfter(exam.getEndTime())) {
                    request.setAttribute("error", "考试已结束。");
                    forwardToExamsPage(request, response, student.getStudentId());
                    return;
                }
                
                // 检查学生是否已经参加过考试
                Score score = scoreDAO.getScoreByExamId(student.getStudentId(), examId);
                if (score != null) {
                    request.setAttribute("error", "你已经参加过该考试");
                    forwardToExamsPage(request, response, student.getStudentId());
                    return;
                }
                
                // 加载考试信息和对应的题目
                List<Question> questions = questionDAO.getQuestionsByExamId(examId);

                if (questions == null || questions.isEmpty()) {
                    request.setAttribute("error", "该考试当前没有题目，请联系管理员。");
                    forwardToExamsPage(request, response, student.getStudentId());
                    return;
                }
                
                request.setAttribute("exam", exam);
                request.setAttribute("questions", questions);
                
                request.getRequestDispatcher("/WEB-INF/views/takeExam.jsp").forward(request, response);
                
            } catch (NumberFormatException e) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            }
        } else if (pathInfo.startsWith("/result/")) {
            // 获取考试ID
            String examIdStr = pathInfo.substring(8);
            try {
                int examId = Integer.parseInt(examIdStr);
                
                // 获取学生ID
                String studentId = ((Student) session.getAttribute("student")).getStudentId();
                
                // 获取考试成绩
                Score score = scoreDAO.getScoreByExamId(studentId, examId);
                if (score == null) {
                    request.setAttribute("error", "未找到该考试成绩");
                    request.getRequestDispatcher("/WEB-INF/views/exams.jsp").forward(request, response);
                    return;
                }
                
                // 设置响应编码
                response.setContentType("text/html; charset=UTF-8");
                // 转发到成绩页面
                request.setAttribute("score", score);
                request.getRequestDispatcher("/WEB-INF/views/examResult.jsp").forward(request, response);
            } catch (NumberFormatException e) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            }
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("student") == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }
        Student student = (Student) session.getAttribute("student");

        try {
            int examId = Integer.parseInt(request.getParameter("examId"));
            Exam exam = examDAO.getExamById(examId); // 获取考试详情
            List<Question> questions = questionDAO.getQuestionsByExamId(examId);

            double totalScore = 0;
            // 假设每道题的分值是总分除以题目数
            double scorePerQuestion = 100.0 / questions.size();

            for (Question question : questions) {
                String questionIdStr = String.valueOf(question.getQuestionId());
                String userAnswer = request.getParameter("q_" + questionIdStr);
                if (userAnswer != null && userAnswer.equals(question.getCorrectAnswer())) {
                    totalScore += scorePerQuestion;
                }
            }

            // 创建Score对象并保存
            Score score = new Score();
            score.setStudentId(student.getStudentId());
            score.setExamId(examId);
            score.setScore(totalScore);
            score.setExamTime(LocalDateTime.now()); // 记录提交时间
            
            // 额外设置exam和student的详细信息
            score.setExam(exam);

            scoreDAO.addScore(score, student);

            // 将本次成绩存入session，以便结果页显示
            request.getSession().setAttribute("lastExamScore", totalScore);
            request.getSession().setAttribute("lastExam", exam); 

            // 重定向到本次考试的结果页面
            response.sendRedirect(request.getContextPath() + "/exams/result/" + examId);

        } catch (Exception e) {
            e.printStackTrace();
            // 如果提交失败，重定向回考试列表并提示错误
            response.sendRedirect(request.getContextPath() + "/exams?error=submitFailed");
        }
    }
    // 辅助方法，用于转发回考试列表页面
    private void forwardToExamsPage(HttpServletRequest request, HttpServletResponse response, String studentId) throws ServletException, IOException {
        List<Exam> exams = examDAO.getAvailableExams(studentId);
        request.setAttribute("exams", exams);
        request.getRequestDispatcher("/WEB-INF/views/exams.jsp").forward(request, response);
    }
}